package com.groupbuying.sysconfig.intercepter;


import com.groupbuying.sysconfig.dao.SysconfigPlatformInfoDao;
import com.groupbuying.sysconfig.domain.SysconfigPlatformInfoDO;
import com.groupbuying.sysconfig.utils.JSONUtils;
import com.groupbuying.sysconfig.utils.RedisUtils;
import com.groupbuying.sysconfig.utils.apiresult.ApiResult;
import com.groupbuying.sysconfig.utils.apiresult.ApiResultCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 功能开启关闭限制
 * @Author Vincentxin
 * @Date 2019-06-24
 */
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);
    @Autowired
    private SysconfigPlatformInfoDao sysconfigPlatformInfoDao;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getRequestURI();
        String indicate = request.getParameter("indicate");
        try{
            //判断请求是否携带了应用的唯一标示
            //TODO 将来需要鉴权的话也是在这里处理
            if (StringUtils.isEmpty(indicate)){
                logger.info("请求Sysconfig中心的路径：{},匹配标示indicate：{}",path,indicate);
               return true;
            }
            String tag = ConfigurationStrategyFactorey.getInstance().selector(path);
            logger.info("匹配标示indicate：{},对应的配置中心：{}",indicate,tag);
            if (StringUtils.isEmpty(tag)) {
                //TODO 这里处理没有匹配到映射地址的请求
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print(JSONUtils.beanToJson(ApiResult.failure(ApiResultCode.NOT_ACCEPTABLE)));
                return false;
            }
            //通过地址映射到对应的tag去数据库查询
            SysconfigPlatformInfoDO sysconfigPlatformInfoDO = null;
            if (redisUtils.isHasKey(indicate+tag)){
                logger.info("匹配标示indicate：{},对应的配置中心：{},缓存命中",indicate,tag);
                 sysconfigPlatformInfoDO = (SysconfigPlatformInfoDO) redisUtils.getValue(indicate+tag);
            }else{
                sysconfigPlatformInfoDO = sysconfigPlatformInfoDao.getConfigurationCenter(indicate,tag);
                if (sysconfigPlatformInfoDO != null){
                    redisUtils.setKey(indicate+tag,sysconfigPlatformInfoDO,36000);
                }
            }
            if (sysconfigPlatformInfoDO == null){
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print(JSONUtils.beanToJson(ApiResult.failure(406,"没有配置开通该功能","")));
                return false;
            }
            ConfigContextHandler.setSysconfigInfo(sysconfigPlatformInfoDO);

        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清空缓存
        ConfigContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }

}
